package com.sunday.aomicaichang.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;
import com.sunday.common.widgets.gridview.NoScrollGridView;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.MakeCommentImageAdapter;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.widgets.FlexibleRatingBar;
import com.sunday.member.entity.UploadImage;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.entity.order.OrderProduct;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.aomicaichang.R.id.flexibleRatingBar;

/**
 * Created by 刘涛 on 2017/8/9.
 */

public class MakeCommentsActivity extends BaseActivity {


    @Bind(R.id.ly_item)
    LinearLayout lyItem;
    @Bind(R.id.btn_commit)
    TextView btnCommit;

    private int maxImageCount = 3;
    private OrderItem order;
    private List<View> viewList = new ArrayList<>();
    private List<ViewsHolder> lsvh = new ArrayList<>();
    private long orderId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assess);
        ButterKnife.bind(this);
        order = (OrderItem) getIntent().getSerializableExtra("order");
        orderId = order.getId();
        addView();
    }

    private void addView() {
        lyItem.removeAllViews();
        if (order.getProducts() != null && order.getProducts().size() > 0) {
            for (int i = 0; i < order.getProducts().size(); i++) {
                productIds.add(String.valueOf(order.getProducts().get(i).getId()));
                initView(order.getProducts().get(i));
                mark++;
            }
        }
    }

    @OnClick(R.id.btn_commit)
    void submit() {
        List<String> upImgList = new ArrayList<>();
        for (int i = 0; i < lsvh.size(); i++) {
            lsvh.get(i).filePaths.clear();
            lsvh.get(i).netImgList.clear();
            if (lsvh.get(i).compressImgList != null && !lsvh.get(i).compressImgList.isEmpty()) {
                upImgList.addAll(lsvh.get(i).compressImgList);
            }
        }
        if (!upImgList.isEmpty()) {
            upLoadImg(UploadUtils.getRequestBody(upImgList));
        } else {
            submitComment();
        }
    }

    private void upLoadImg(RequestBody requestBody) {
        showLoadingDialog(0);
        Call<ResultDO<List<UploadImage>>> call = MemberClient.getApiAdapter().uploadMulti(requestBody);
        call.enqueue(new Callback<ResultDO<List<UploadImage>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<UploadImage>>> call, Response<ResultDO<List<UploadImage>>> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    List<UploadImage> filePaths = response.body().getResult();

                    for (ViewsHolder vh : lsvh) {
                        for (int j = 0; j < vh.compressImgList.size(); j++) {
                            for (int i = 0; i < filePaths.size(); i++) {
                                if (vh.compressImgList.get(j).substring(vh.compressImgList.get(j).lastIndexOf('/') + 1, vh.compressImgList.get(j).length()).
                                        equals(filePaths.get(i).getOldName())) {
                                    vh.netImgList.add(filePaths.get(i).getHalfPath());
                                    break;
                                }
                            }
//                            if (vh.filePaths.containsKey(filePaths.get(i).getOldName())) {
//                                vh.filePaths.put(filePaths.get(i).getOldName(), filePaths.get(i).getHalfPath());
//                                vh.netImgList.add(filePaths.get(i).getHalfPath());
//                            }
                        }
                    }
                    submitComment();

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<UploadImage>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }

    private List<String> productIds = new ArrayList<>();
    private List<String> contents = new ArrayList<>();
    private List<String> scores = new ArrayList<>();
    private List<String> imgs = new ArrayList<>();

    private void submitComment() {
        imgs.clear();
        contents.clear();
        scores.clear();
        for (int i = 0; i < lsvh.size(); i++) {
            ViewsHolder vh = lsvh.get(i);
            int score = (int) vh.flexibleRatingBar.getRating();
            if (score == 0) {
                scores.add("5");
            } else {
                scores.add(String.valueOf(score));
            }
            String content = vh.editText.getText().toString();
            if (TextUtils.isEmpty(content)) {
                contents.add("系统默认好评");
            } else {
                contents.add(content);
            }
            final int num = vh.netImgList.size();
            if (num < 3) {
                for (int j = 0; j < 3 - num; j++) {
                    vh.netImgList.add("noImage");
                }
            }
            imgs.addAll(vh.netImgList);
        }
        commit();
    }

    private void commit() {
        String images = StringUtils.listToString(imgs);
        String ids = StringUtils.listToString(productIds);
        String content = StringUtils.listToString(contents);
        String score = StringUtils.listToString(scores);
        showLoadingDialog(0);
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"orderId", "productIds", "contents", "scores", "images", "nonce"};
        String[] str2 = new String[]{String.valueOf(orderId), ids, content, score, images, nonce};
        Call<ResultDO> call = ApiClient.getApiAdapter().comment(orderId, ids, content, score, images, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "评论成功");
                    finish();
                } else {

                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }


    private int mark = 0;

    private void initView(OrderProduct product) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_assess, null);
        lyItem.addView(view);
        view.setId(mark);
        getViewInstance(view, product);
    }

    private void getViewInstance(View childView, OrderProduct product) {
        final ViewsHolder vh = new ViewsHolder();
        vh.id = childView.getId();//标识viewholder 存储唯一的childview 信息
        vh.imgTop = (ImageView) childView.findViewById(R.id.img_top);
        vh.tvName = (TextView) childView.findViewById(R.id.tv_name);
        vh.flexibleRatingBar = (FlexibleRatingBar) childView.findViewById(flexibleRatingBar);
        vh.editText = (EditText) childView.findViewById(R.id.edit_text);
        vh.noScrollGridView = (NoScrollGridView) childView.findViewById(R.id.images);
        Picasso.with(mContext)
                .load(product.getImage())
                .error(R.mipmap.ic_product)
                .into(vh.imgTop);
        vh.tvName.setText(product.getName());
        //final List<Object> dataSet =product.getImages();
        vh.selectImgList.addAll(vh.imgList);
        vh.selectImgList.add(R.mipmap.add);
        vh.adapter = new MakeCommentImageAdapter(mContext, vh.selectImgList);
        vh.noScrollGridView.setAdapter(vh.adapter);
        vh.adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                if (v.getId() == R.id.delete_image) {
                    vh.selectImgList.remove(position);
                    vh.adapter.notifyDataSetChanged();
                } else if (position == vh.selectImgList.size() - 1) {
                    Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
                    // 是否显示拍摄图片
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大可选择图片数量
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxImageCount);
                    // 选择模式
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, vh.imgList);
                    intent.putExtra("position", vh.id);
                    startActivityForResult(intent, 0);
                }
            }
        });
        lsvh.add(vh);
        viewList.add(childView);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        int position = data.getIntExtra("position", 0);
        ViewsHolder vh = lsvh.get(position);
        vh.imgList.clear();
        vh.compressImgList.clear();
        vh.imgList.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
        for (String item : vh.imgList) {
            if (!item.startsWith("http")) {
                vh.compressImgList.add(ImageUtils.getCompressImagePath(item));
            }
        }
        vh.selectImgList.clear();
        vh.selectImgList.addAll(vh.imgList);
        vh.selectImgList.add(R.mipmap.add);
        vh.adapter.notifyDataSetChanged();
    }

    public class ViewsHolder {

        private int id = -1;
        private ImageView imgTop;
        private TextView tvName;
        private FlexibleRatingBar flexibleRatingBar;
        private EditText editText;
        private NoScrollGridView noScrollGridView;

        private MakeCommentImageAdapter adapter;

        private ArrayList<Object> selectImgList = new ArrayList<>();
        private ArrayList<String> imgList = new ArrayList<>();
        private HashMap<String, String> filePaths = new HashMap<>();//用于存放上传返回后的文件路径
        private List<String> netImgList = new ArrayList<>();
        private List<String> compressImgList=new ArrayList<>();
    }
}
